<?php
namespace App\Admin\Controllers\CustomerDelivery;

use App\Admin\Ajax\CustomerDelivery\DeliveryCnAjax;
use App\Exporter\CustomerDelivery\CnExporter;
use App\Models\Basics\SysArea;
use App\Models\Basics\SysCountry;
use App\Models\Basics\SysPlat;
use App\Models\CustomerDelivery\CustomerDelivery;
use App\Models\CustomerDelivery\CustomerDeliveryDetail;
use App\Models\Sys\Logs;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Layout\Content;
use Illuminate\Support\Facades\Request;
use Maatwebsite\Excel\Facades\Excel;
class DeliveryCnController extends AdminController{

    protected $title = '国内发货';

    protected $filters = [
        'start_date' => null,
        'end_date' => null,
        'order_no' => null,
        'tracking_no' => null,
        'plat_id' => null,
        'area_id' => null,
        'country_id' => null,
        'seller_id' => null,
        'status' => null,
        'logistics_status' => null,
        'sku' => null,
    ];

    protected function grid()
    {
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->_paginator($query);
        $action = getAction($filtersField);
        $filtersBlade = [];
        $filtersBlade['start_date'] = $this->filters['start_date'];
        $filtersBlade['end_date'] = $this->filters['end_date'];
        $filtersBlade['order_no'] = $this->filters['order_no'];
        $filtersBlade['tracking_no'] = $this->filters['tracking_no'];
        $filtersBlade['plat_id'] = getOptions(SysPlat::options(), $this->filters['plat_id']);
        $filtersBlade['area_id'] = getOptions(SysArea::options(), $this->filters['area_id']);
        $filtersBlade['country_id'] = getOptions(SysCountry::options(), $this->filters['country_id']);
        $filtersBlade['seller_id'] = getOptions(User::getSellerOptions(), $this->filters['seller_id']);
        $filtersBlade['status'] = getOptions(CustomerDeliveryDetail::$_status, $this->filters['status']);
        $filtersBlade['logistics_status'] = getOptions(CustomerDeliveryDetail::$_logisticsStatus, $this->filters['logistics_status']);
        $filtersBlade['sku'] = $this->filters['sku'];

        return view('customer-delivery.delivery-cn.index', compact('paginator','action','filtersBlade'));
    }

    private function _getFilters($filtersField){
        $filters = [];
        foreach ($filtersField as $field){
            $filters[$field] = request($field);
        }
        return $filters;
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function _initQuery($filters){
        $query = CustomerDelivery::query()
            ->where('delivery_type', CustomerDelivery::DELIVERY_TYPE_CN) //发货方式 (3:国内仓)
            ->orderBy('id', 'DESC');

        foreach ($filters as $field => $filter){
            if(!$filter)continue;
            if($field == 'start_date'){
                $query->where('delivered_at','>=',$filter.' 00:00:00');
            }
            if($field == 'end_date'){
                $query->where('delivered_at','<=',$filter.' 23:59:59');
            }
            if($field == 'plat_id'){
                $query->where('plat_id', $filter);
            }
            if($field == 'sku'){
                $query->whereHas('detail.sku', function ($query) use($filter){
                    $query->where('psku_code', 'like', "%{$filter}%")
                        ->orWhere('psku_cn', 'like', "%{$filter}%");
                });
            }
            if($field == 'order_no'){
                $query->where('order_no', $filter)
                    ->orWhere('delivery_no', $filter);
            }
            if($field == 'tracking_no'){
                $query->whereHas('logistics', function ($query) use($filter){
                    $query->where('tracking_no', $filter);
                });
            }
            //if(in_array($field,['delivery_no','order_no','plat_id','area_id','country_id','seller_id','status','logistics_status'])){
            if(in_array($field,['plat_id','area_id','country_id','seller_id','status','logistics_status'])){
                $query->where($field,$filter);
            }
        }
        return $query;
    }

    private function _paginator($query){
        return $query->paginate((int) (request("per_page",10)))->appends(Request::input());
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new DeliveryCnAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }

    public function modal(){
        $action = request('action');
        $param = request('param');
        $modal = new DeliveryCnAjax();
        return $param ? call_user_func([$modal,$action],$param) : call_user_func([$modal,$action]);
    }

    public function download($id){
        $delivery = CustomerDelivery::query()->findOrFail($id);
        return Excel::download(new CnExporter($delivery), $delivery->delivery_no.'.xlsx');
    }

    public function update($id){
        $name = Request::get('name');
        $value = Request::get('value');
        $deliveryObj = CustomerDelivery::query()->findOrFail($id);
        if (empty($deliveryObj)) return response()->json(['status' => false, 'message' => '数据异常!']);
        $deliveryObj->{$name} = $value;
        if($deliveryObj->save()){
            return response()->json(['status' => true, 'message' => '更新成功']);
        }else{
            return response()->json(['status' => false, 'message' => '更新失败']);
        }
    }

    protected function detail($id){

        $delivery = CustomerDelivery::query()->findOrFail($id);
        $logs = Logs::getLogs(Logs::CUSTOMER_ORDER_CN,$id);

        return view('customer-delivery.delivery-cn-detail.index', compact('delivery','logs'));
    }

    public function create(Content $content){

        return $content
            ->title($this->title())
            ->description($this->description['create'] ?? trans('admin.create'))
            ->body(view('customer-delivery.delivery-cn-create.index'));
    }
}
